package cn.bugstack.ai_autoclassification_qwen.service.impl;

import cn.bugstack.ai_autoclassification_qwen.domain.tProduct;
import cn.bugstack.ai_autoclassification_qwen.repository.tProductRepository;
import cn.bugstack.ai_autoclassification_qwen.service.BatchProductClassificationService;
import cn.bugstack.ai_autoclassification_qwen.service.TProductClassificationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
public class BatchProductClassificationServiceimpl implements BatchProductClassificationService {
    private final tProductRepository productRepository;
    private final TProductClassificationService classificationService;

    private static final int BATCH_SIZE = 100;     // 每批处理100条
    private static final int SLEEP_MS = 100;       // 模型限流：每次调用后休眠100ms

    public void classifyAllProducts() {

        while (true) {
            // 每次都从“剩下的未分类数据”的第 0 页取 100 条
            Pageable pageable = PageRequest.of(0, BATCH_SIZE, Sort.by("id").ascending());
            Page<tProduct> productPage =
                    productRepository.findByPredictedCategoryCodeIsNull(pageable);

            List<tProduct> products = productPage.getContent();
            if (products.isEmpty()) {
                System.out.println("没有需要分类的数据了，任务结束。");
                break;
            }

            System.out.println("本批次处理数量：" + products.size());

            for (tProduct product : products) {
                classifySafe(product.getId());
                try {
                    Thread.sleep(SLEEP_MS);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }

    }

    /** 单条调用带重试 */
    private void classifySafe(Long productId) {
//        int maxRetry = 0;
//        classificationService.classifyProduct(productId);

        try {
            classificationService.classifyProduct(productId);
//            return;
        } catch (Exception ex) {
            System.err.println("最终失败，跳过该条：" + productId);
        }

//        for (int i = 1; i <= maxRetry; i++) {
//            try {
//                classificationService.classifyProduct(productId);
//                return;
//            } catch (Exception ex) {
//                System.err.println("分类失败 id=" + productId + "，第 " + i + " 次重试");
//                if (i == maxRetry) {
//                    System.err.println("最终失败，跳过该条：" + productId);
//                }
//            }
//        }
    }
}
